//
//  TMWindow.m
//  Textmaster
//
//  Created by Anshu Chimala on 1/1/10.
//  Copyright 2010 MediaLocal LLC. All rights reserved.
//

#import "TMWindow.h"

@implementation TMFadePanel

- (void)awakeFromNib {
	[self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
	[self setMovableByWindowBackground:YES];
}

- (void)makeKeyAndOrderFront:(id)sender {
	NSRect visibleFrame = [[NSScreen mainScreen] visibleFrame];
	NSRect windowFrame = [self frame];
	[self setFrame:NSMakeRect((visibleFrame.size.width - windowFrame.size.width) * 0.5,
							  (visibleFrame.size.height - windowFrame.size.height) * (9.0/10.0),
							  windowFrame.size.width, windowFrame.size.height) display:YES];
	
	[[NSAnimationContext currentContext] setDuration:.15];
	[super makeKeyAndOrderFront:sender];
	[[self animator] setAlphaValue:1];
}

- (void)orderOut:(id)sender {
	[[NSAnimationContext currentContext] setDuration:.15];
	[super performSelector:@selector(performClose:) withObject:sender afterDelay:.15];
	[[self animator] setAlphaValue:0];
}

@end


@implementation TMWindow
@synthesize needsToPaste = _needsToPaste;

- (void)awakeFromNib {
	[super awakeFromNib];
	
	NSButton *zoomButton = [self standardWindowButton:NSWindowZoomButton];
	NSButton *minButton = [self standardWindowButton:NSWindowMiniaturizeButton];
	NSButton *closeButton = [self standardWindowButton:NSWindowCloseButton];
	[zoomButton setHidden:YES];
	[minButton setHidden:YES];
	[closeButton setHidden:YES];
	//[self setFloatingPanel:YES];
	
	_needsToPaste = NO;
}

- (void)doPaste {
	if(!_needsToPaste)
		return;
	
	// Completely stolen from JumpCut (jumpcut.sf.net)
	// Sends a fake cmd+v to paste stuff
	NSNumber *keyCode = [NSNumber numberWithInt:0x9];
	CGKeyCode veeCode = (CGKeyCode)[keyCode intValue];
	CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, true ); // Command down
	CGPostKeyboardEvent( (CGCharCode)'v', veeCode, true ); // V down 
	CGPostKeyboardEvent( (CGCharCode)'v', veeCode, false ); //  V up 
	CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, false ); // Command up
	
	_needsToPaste = NO;
}

- (void)activationHack {
	[NSApp hide:self];
	[NSApp unhideWithoutActivation];
}

- (void)performClose:(id)sender {
	[super performClose:sender];
	
	[self performSelector:@selector(activationHack) withObject:nil afterDelay:.05];
	if(_needsToPaste)
		[self performSelector:@selector(doPaste) withObject:nil afterDelay:0.2];
}

@end
